package com.wyclabs.cardmaker.cells;
import com.jfoenix.controls.JFXTextField;
import com.wyclabs.cardmaker.Card;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.TableCell;
import lombok.NoArgsConstructor;

/**
 * @author TylerW
 * @date 06/22/21 10:59 AM
 */
@NoArgsConstructor
public class EditingCell extends TableCell<Card, String> {

    private JFXTextField textArea;

    @Override
    public void startEdit() {
        if (!isEmpty()) {
            super.startEdit();
            createTextField();
            setText(null);
            setGraphic(textArea);
            textArea.selectAll();
        }
    }

    @Override
    public void cancelEdit() {
        super.cancelEdit();
        setText(getItem());
        setGraphic(null);
    }

    @Override
    public void updateItem(String item, boolean empty) {
        super.updateItem(item, empty);
        System.out.println(item);
        if (empty) {
            setText(null);
            setGraphic(null);
        } else {
            if (isEditing()) {
                if (textArea != null) {
                    textArea.setText(getString());
                }
                setText(null);
                setGraphic(textArea);
            } else {
                setText(getString());
                setGraphic(null);
            }
        }
    }

    private void createTextField() {
        textArea = new JFXTextField(getString());
        textArea.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2);
        textArea.focusedProperty().addListener(
            (ObservableValue<? extends Boolean> arg0,
             Boolean arg1, Boolean arg2) -> {
                if (!arg2) {
                    commitEdit(textArea.getText());
                }
            });
    }

    private String getString() {
        return getItem() == null ? "" : getItem();
    }
}


